# 推荐记录管理的视图文件
from django.shortcuts import render
from django.http import HttpResponse
from django.core.paginator import Paginator
from django.db.models import Q
from datetime import datetime

from myadmin.models import Users, RecommendationRecords

# 推荐记录管理
def index(request, pIndex=1):
    """推荐记录列表页"""
    rlist = RecommendationRecords.objects.select_related('user').all()
    mywhere = []
    
    # 排序处理
    sort = request.GET.get('sort', None)
    order = request.GET.get('order', 'asc')
    if sort:
        if order == 'desc':
            sort = f'-{sort}'
        try:
            rlist = rlist.order_by(sort)
            mywhere.extend([f'sort={sort.replace("-", "")}', f'order={order}'])
        except:
            pass
    
    # 搜索处理
    kw = request.GET.get("keyword", None)
    if kw:
        rlist = rlist.filter(
            Q(user__username__contains=kw) | 
            Q(content__contains=kw) |
            Q(recommendation_type__contains=kw)
        )
        mywhere.append(f'keyword={kw}')
    
    # 类型筛选
    rtype = request.GET.get('recommendation_type', '')
    if rtype:
        rlist = rlist.filter(recommendation_type=rtype)
        mywhere.append(f'recommendation_type={rtype}')
    
    # 推荐依据筛选
    based_on = request.GET.get('based_on', '')
    if based_on:
        rlist = rlist.filter(based_on=based_on)
        mywhere.append(f'based_on={based_on}')
    
    # 接受状态筛选
    is_accepted = request.GET.get('is_accepted', '')
    if is_accepted == 'True':
        rlist = rlist.filter(is_accepted=True)
        mywhere.append('is_accepted=True')
    elif is_accepted == 'False':
        rlist = rlist.filter(is_accepted=False)
        mywhere.append('is_accepted=False')
    elif is_accepted == 'None':
        rlist = rlist.filter(is_accepted__isnull=True)
        mywhere.append('is_accepted=None')
    
    # 分页处理
    pIndex = int(pIndex)
    page = Paginator(rlist, 10)  # 每页10条
    maxpages = page.num_pages
    if pIndex > maxpages:
        pIndex = maxpages
    if pIndex < 1:
        pIndex = 1
    list2 = page.page(pIndex)
    plist = page.page_range
    
    # 获取所有用户（用于筛选框）
    users = Users.objects.all()
    
     # 传递推荐类型和依据的选项列表到模板
    type_choices = RecommendationRecords.RECOMMENDATION_TYPE_CHOICES
    based_choices = RecommendationRecords.BASED_ON_CHOICES
    
    context = {
        "recordlist": list2,
        'users': users,
        'plist': plist,
        'pIndex': pIndex,
        'maxpages': maxpages,
        'mywhere': mywhere,
        'selected_type': rtype,
        'selected_based': based_on,
        'selected_accepted': is_accepted,
        'type_choices': type_choices,
        'based_choices': based_choices
    }
    return render(request, "myadmin/recommendations/index.html", context)

def add(request):
    """加载推荐记录添加表单"""
    users = Users.objects.all()
    # 获取推荐类型和依据的选项列表
    type_choices = RecommendationRecords.RECOMMENDATION_TYPE_CHOICES
    based_choices = RecommendationRecords.BASED_ON_CHOICES
    context = {
        'users': users,
        'type_choices': type_choices,
        'based_choices': based_choices
    }
    return render(request, "myadmin/recommendations/add.html", context)

def insert(request):
    """执行推荐记录添加"""
    try:
        ob = RecommendationRecords()
        ob.user_id = request.POST.get('user_id')
        ob.recommendation_type = request.POST.get('recommendation_type')
        ob.based_on = request.POST.get('based_on')
        ob.content = request.POST.get('content')
        
        # 处理可选字段
        is_accepted = request.POST.get('is_accepted')
        if is_accepted == 'True':
            ob.is_accepted = True
        elif is_accepted == 'False':
            ob.is_accepted = False
        else:
            ob.is_accepted = None
            
        ob.feedback = request.POST.get('feedback', '')
        
        # 处理时间（如果提供了时间则使用，否则默认当前时间）
        time_str = request.POST.get('recommendation_time')
        if time_str:
            try:
                # 尝试解析空格分隔格式（YYYY-MM-DD HH:mm:ss）
                ob.recommendation_time = datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S")
            except ValueError:
                # 解析失败则尝试T分隔格式（YYYY-MM-DDThh:mm:ss）
                ob.recommendation_time = datetime.strptime(time_str, "%Y-%m-%dT%H:%M:%S")
        
        ob.save()
        context = {'info': "添加成功！"}
    except Exception as err:
        print(err)
        context = {'info': "添加失败！"}
    return render(request, "myadmin/info.html", context)

def edit(request, rid=0):
    """加载推荐记录编辑表单"""
    try:
        ob = RecommendationRecords.objects.get(recommendation_id=rid)
        users = Users.objects.all()
        type_choices = RecommendationRecords.RECOMMENDATION_TYPE_CHOICES
        based_choices = RecommendationRecords.BASED_ON_CHOICES
        context = {
            'record': ob,
            'users': users,
            'type_choices': type_choices,
            'based_choices': based_choices
        }
        return render(request, "myadmin/recommendations/edit.html", context)
    except Exception as err:
        print(err)
        context = {'info': "没有找到要修改的信息！"}
    return render(request, "myadmin/info.html", context)

def update(request, rid):
    """执行推荐记录编辑"""
    try:
        # 获取推荐记录对象
        ob = RecommendationRecords.objects.get(recommendation_id=rid)
        
        # 验证必填字段
        required_fields = {
            'user_id': '用户',
            'recommendation_type': '推荐类型',
            'based_on': '推荐依据',
            'content': '推荐内容'
        }
        for field, label in required_fields.items():
            if not request.POST.get(field):
                raise ValueError(f'{label}为必填项！')
        
        # 处理字段更新
        ob.user_id = request.POST.get('user_id')
        ob.recommendation_type = request.POST.get('recommendation_type')
        ob.based_on = request.POST.get('based_on')
        ob.content = request.POST.get('content').strip()
        
        # 处理接受状态
        is_accepted = request.POST.get('is_accepted')
        if is_accepted == 'True':
            ob.is_accepted = True
        elif is_accepted == 'False':
            ob.is_accepted = False
        else:
            ob.is_accepted = None
            
        # 处理反馈内容
        ob.feedback = request.POST.get('feedback', '').strip()
        
        # 处理时间
        time_str = request.POST.get('recommendation_time')
        if time_str:
            try:
                ob.recommendation_time = datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S")
            except ValueError:
                ob.recommendation_time = datetime.strptime(time_str, "%Y-%m-%dT%H:%M:%S")
        
        # 验证用户是否存在
        if not Users.objects.filter(user_id=ob.user_id).exists():
            raise ValueError('用户不存在！')
        
        ob.save()
        context = {'info': "修改成功！"}
    
    except RecommendationRecords.DoesNotExist:
        context = {'info': "修改失败：推荐记录不存在！"}
    except ValueError as e:
        context = {'info': f"修改失败：{str(e)}"}
    except Exception as e:
        print(f"修改错误详情：{str(e)}")
        context = {'info': f"修改失败：{str(e)}"}
    
    return render(request, "myadmin/info.html", context)

def delete(request, rid=0):
    """执行推荐记录删除"""
    try:
        ob = RecommendationRecords.objects.get(recommendation_id=rid)
        ob.delete()
        context = {'info': "删除成功！"}
    except RecommendationRecords.DoesNotExist:
        context = {'info': "删除失败：推荐记录不存在！"}
    except Exception as err:
        print(f"删除推荐记录时出错: {err}")
        context = {'info': "删除失败：发生未知错误！"}
    return render(request, "myadmin/info.html", context)